package data_structures_and_algorithms.list_node;

import common.ListNode;

/**
 * @ClassName Code_0021_mergeTwoSortedLists
 * @Description: https://leetcode.cn/problems/merge-two-sorted-lists/
 * @Author: yongliang.ma
 * @Create_time:2022/10/26 21:59
 */
public class Code_0021_mergeTwoSortedLists {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(0);
        ListNode cur = head, next = null;

        while (list1 != null && list2 != null){
            if (list1.val < list2.val){
                // 取list1中节点
                next = list1.next;

                cur.next = list1;

                cur = cur.next;
                list1 = next;
            }else {
                // 取list2中节点
                next = list2.next;

                cur.next = list2;

                cur = cur.next;
                list2 = next;
            }
        }
        if (list1 != null){
            cur.next = list1;
        }
        if (list2 != null)
            cur.next = list2;

        return head.next;
    }
}
